/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ManejoExc.EmpresaException;
import Negocio.Empresa;
import Negocio.Parcela;
import Negocio.Plantacion;
import java.util.Iterator;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Diego
 */
public class FrmParcela extends javax.swing.JDialog {
    private Empresa unaEmpresa;
    private Plantacion unaPlantacion;
    private Parcela unaParcela;
    private DefaultListModel modelPlantaciones = new DefaultListModel();
    private DefaultListModel Modelo = new DefaultListModel();

    /**
     * Creates new form FrmParcela
     */
    public FrmParcela(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
        public FrmParcela(java.awt.Frame parent, boolean modal,Empresa unaEmpresa) {
        super(parent, modal);
        initComponents();
        this.unaEmpresa = unaEmpresa;
        this.lstPlantaciones.setModel(modelPlantaciones);
        this.lstParcelas.setModel(Modelo);
        this.inicializar();
    }
        
        public void inicializar(){
            this.cargarPlantaciones();
            this.unaPlantacion = null;
        }
        
        public void cargarPlantaciones(){
            this.modelPlantaciones.clear();
            Iterator it = this.unaEmpresa.getPlantaciones().iterator();
            if(this.unaEmpresa.getPlantaciones() != null && this.unaEmpresa.getPlantaciones().size() > 0){
                while(it.hasNext()){
                    this.modelPlantaciones.addElement((Plantacion) it.next());
                }
            }else{
                this.modelPlantaciones.addElement("No se Encontraron Plantaciones");
            }
        }
        
        public void cargarParcelas(){
            this.Modelo.clear();
            Iterator it = this.unaPlantacion.getParcelas().iterator();
            if(this.unaPlantacion.getParcelas() != null && this.unaPlantacion.getParcelas().size() > 0){
            while(it.hasNext()){ 
                this.Modelo.addElement((Parcela) it.next());
            }
            }else{
                this.Modelo.addElement("No se encontraron Parcelas para la plantacion seleccionada");
            }
        }

    public void  cargarDatosParcela(){
        this.TxtNro.setText(Integer.toString(this.unaParcela.getNroParcela()));
        this.txtDescripcion.setText(this.unaParcela.getDescripcion());
        this.TxtNro.setEnabled(true);
        this.txtDescripcion.setEnabled(true);
        this.BtnNuevo.setEnabled(false);
        this.BtnGuardar.setEnabled(true);
        this.BtnCancelar.setEnabled(true);
        this.BtnBorrar.setEnabled(true);
    }
    public void limpiarCampos(){
        this.BtnCancelar.setEnabled(true);
        this.BtnGuardar.setEnabled(true);
        this.BtnNuevo.setEnabled(false);
        this.TxtNro.setEnabled(true);
        this.txtDescripcion.setEnabled(true);
        this.unaParcela=null;
        this.TxtNro.setText("");
        this.txtDescripcion.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        lstPlantaciones = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstParcelas = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        BtnCancelar = new javax.swing.JButton();
        BtnGuardar = new javax.swing.JButton();
        BtnNuevo = new javax.swing.JButton();
        BtnAceptar = new javax.swing.JButton();
        BtnBorrar = new javax.swing.JButton();
        TxtNro = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lstPlantaciones.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstPlantaciones.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstPlantacionesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lstPlantaciones);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Plantaciones");

        lstParcelas.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        lstParcelas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstParcelasMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(lstParcelas);

        jLabel2.setText("Nro");

        jLabel3.setText("Desripcion");

        txtDescripcion.setColumns(20);
        txtDescripcion.setRows(5);
        txtDescripcion.setEnabled(false);
        jScrollPane3.setViewportView(txtDescripcion);

        BtnCancelar.setText("Cancelar");
        BtnCancelar.setEnabled(false);
        BtnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelarActionPerformed(evt);
            }
        });

        BtnGuardar.setText("Guardar");
        BtnGuardar.setEnabled(false);
        BtnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnGuardarActionPerformed(evt);
            }
        });

        BtnNuevo.setText("Nuevo");
        BtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnNuevoActionPerformed(evt);
            }
        });

        BtnAceptar.setText("Aceptar");
        BtnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnAceptarActionPerformed(evt);
            }
        });

        BtnBorrar.setText("Borrar");
        BtnBorrar.setEnabled(false);
        BtnBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnBorrarActionPerformed(evt);
            }
        });

        TxtNro.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###"))));
        TxtNro.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                            .addComponent(jScrollPane3)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel3)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18)
                                        .addComponent(TxtNro, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 80, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(BtnAceptar, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(BtnNuevo)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(BtnGuardar)
                                        .addGap(1, 1, 1)
                                        .addComponent(BtnBorrar)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(BtnCancelar))))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(TxtNro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(BtnCancelar)
                            .addComponent(BtnGuardar)
                            .addComponent(BtnNuevo)
                            .addComponent(BtnBorrar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(BtnAceptar)
                        .addGap(23, 23, 23))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 464, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BtnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAceptarActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_BtnAceptarActionPerformed
    
    private void BtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnNuevoActionPerformed
        // TODO add your handling code here:
        this.limpiarCampos();
    }//GEN-LAST:event_BtnNuevoActionPerformed

    private void BtnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnGuardarActionPerformed
        // TODO add your handling code here:
        try{
        if(this.unaParcela == null){
            this.unaPlantacion.nuevaParcela(Integer.parseInt(this.TxtNro.getText()),this.txtDescripcion.getText());
        }else{

            this.unaPlantacion.actualizarParcela(this.unaParcela,Integer.parseInt(this.TxtNro.getText()),this.txtDescripcion.getText());
            
        }
        this.cargarParcelas();
        this.limpiarCampos();
        this.BtnBorrar.setEnabled(false);
        this.BtnCancelar.setEnabled(false);
        this.BtnGuardar.setEnabled(false);
        this.BtnNuevo.setEnabled(true);

        }
        catch(EmpresaException ex){
            
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
        catch (NumberFormatException ex){
            JOptionPane.showMessageDialog(this, "Verifique el valor ingresado para el Nro de Parcela");
            this.TxtNro.selectAll();
        }
        
        
    }//GEN-LAST:event_BtnGuardarActionPerformed

    private void lstPlantacionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstPlantacionesMouseClicked
        // TODO add your handling code here:
        this.unaPlantacion = (Plantacion) this.modelPlantaciones.getElementAt(this.lstPlantaciones.getSelectedIndex());
        this.TxtNro.setText("");
        this.txtDescripcion.setText("");
        this.TxtNro.setEnabled(false);
        this.txtDescripcion.setEnabled(false);
        this.cargarParcelas();
    }//GEN-LAST:event_lstPlantacionesMouseClicked

    private void lstParcelasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstParcelasMouseClicked
        // TODO add your handling code here:
        this.unaParcela = (Parcela) this.Modelo.getElementAt(this.lstParcelas.getSelectedIndex());
        this.cargarDatosParcela();
    }//GEN-LAST:event_lstParcelasMouseClicked

    private void BtnBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnBorrarActionPerformed
        // TODO add your handling code here:
        int mc,bc,ch=1;
        mc = JOptionPane.QUESTION_MESSAGE;  
        bc = JOptionPane.YES_NO_CANCEL_OPTION;
        ch = JOptionPane.showConfirmDialog (this, "Desea borrar la Parcela seleccionada?", "Confirmacion", bc, mc); 
        if(ch == 0){
            this.unaPlantacion.quitarParcela(this.unaParcela);
            this.BtnBorrar.setEnabled(false);
            this.BtnCancelar.setEnabled(false);
            this.BtnGuardar.setEnabled(false);
            this.BtnNuevo.setEnabled(true);
            this.txtDescripcion.setText("");
            this.unaParcela=null;
            this.txtDescripcion.setEnabled(false);
            this.cargarParcelas();
        } 
    }//GEN-LAST:event_BtnBorrarActionPerformed

    private void BtnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelarActionPerformed
        // TODO add your handling code here:
        this.BtnCancelar.setEnabled(false);
        this.BtnGuardar.setEnabled(false);
        this.BtnNuevo.setEnabled(true);
        this.TxtNro.setEnabled(false);
        this.BtnBorrar.setEnabled(false);
        this.txtDescripcion.setEnabled(false);
        this.unaParcela=null;
        this.TxtNro.setText("");
        this.txtDescripcion.setText("");
    }//GEN-LAST:event_BtnCancelarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmParcela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog 
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmParcela dialog = new FrmParcela(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });*/
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnAceptar;
    private javax.swing.JButton BtnBorrar;
    private javax.swing.JButton BtnCancelar;
    private javax.swing.JButton BtnGuardar;
    private javax.swing.JButton BtnNuevo;
    private javax.swing.JFormattedTextField TxtNro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList lstParcelas;
    private javax.swing.JList lstPlantaciones;
    private javax.swing.JTextArea txtDescripcion;
    // End of variables declaration//GEN-END:variables
}
